/**
 * 
 */
package com.nextive.interview.util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContactsEntity;

import com.nextive.interview.dto.ContactDetails;

import static com.nextive.interview.ApplicationManager.getAppContext;

/**
 * This class contains several method needed when dealing with <code>Contact App</code>.
 * @author Cesar Roman
 *
 */
public class PhoneContactsUtil {
	
	/**
	 * It queries <code>Contact App</code> in order to obtain information about a contact.
	 * Contact id comes within the <code>contactUri</code>.
	 * @param contactUri
	 * @return the contact details
	 */
	public static ContactDetails getContactDetails(Uri contactUri) {
		
		Context context = getAppContext();
		ContentResolver contentResolver = context.getContentResolver();
		
		long contactId = ContentUris.parseId(contactUri);
		Cursor rawContactsEntityCursor = contentResolver.query(RawContactsEntity.CONTENT_URI, 
				new String[] { 
				RawContactsEntity.MIMETYPE,
				RawContactsEntity.DATA1,
				RawContactsEntity.CONTACT_ID }, RawContactsEntity.CONTACT_ID + "=?", new String[] { new Long(contactId).toString() }, null);
		
		String name = null;
		String email = null;
		try {
			
			String dataType;
			while (rawContactsEntityCursor.moveToNext()) {
				
				dataType = rawContactsEntityCursor.getString(0);
				if (dataType != null)
					if (Email.CONTENT_ITEM_TYPE.equals(dataType)) {
					
					// add pair id - email
					email = rawContactsEntityCursor.getString(1);
					
					} else if (StructuredName.CONTENT_ITEM_TYPE.equals(dataType)) {
						
						name = rawContactsEntityCursor.getString(1);
					}
			}
			
		} finally {
			rawContactsEntityCursor.close();
		}

		return new ContactDetails(name, email);
		
	}

}